<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/7/16
 * Time: 10:42
 */
namespace app\home\controller;
use think\Controller;
use think\Db;
use think\Session;
use think\request;

/**
 *
 * 杭州市民卡快捷支付
 */
class Apaycard extends Base{
    //市民卡选择银行卡
    public function uppage()
    {
        //先必须实名认证
        $ste=Db::name('user_certification')->where("uid=".Session::get('uid')." and status=1")->find();
        if($ste==''){
            $this->success('请先进行实名认证','/home/certification/index');
        }
        //充值金额
        $amount=$_GET['toamount'];
        //手续费
        $charge=$_GET['charge'];
        $charge=round($charge,2);
        //总金额
        $toamount=round(($amount+$charge),2);
        $this->assign('amount',$amount);
        $this->assign('charge',$charge);
        $this->assign('toamount',$toamount);
        //此用户是否签约了银行卡
        //流水号
        $order=orderNum();
        $str="version=1.0.0&transCode=BQP0005&reqSeq=".$order."&merCode=330100710271&chainNo=004&merCustId=".Session::get('uid');
        $pfxpath='http://test.lcqjgj.com/static/home/lc.pfx';
        $pfxpwd='Lczc_164';
        $sign=$this->sign(iconv('UTF-8','GBK',$str),$pfxpath,$pfxpwd);
        $data='{"version":"1.0.0","transCode":"BQP0005","reqSeq":"'.$order.'",
		"merCode":"330100710271","chainNo":"004","merCustId":"'.Session::get('uid').'","sign":"'.$sign.'"}';
        $data=iconv('UTF-8','GBK',$data);
        $data=base64_encode($data);
        $data=str_replace('+','#',$data);  //+替换成#
        $url='https://hpay.96225.com/HzsmkBQPay/merBQPay.do';
        $res=$this->https_request($url,$data);
        //$res=iconv('GBK','UTF-8',$res);
        $res= json_decode($res,true);
        //var_dump($res);die;
        if($res['number']==0)
        {
            return  "<script>alert('您暂未签约银行，请先签约银行');window.location.href='".url('/home/Apaycard/pageadd')."?toamount=$toamount"."'</script>";
        }else{

            foreach($res['cards'] as $k=>$v)
            {
                $res['cards'][$k]['vimg']=Db::name('banks')->where('bankName',$v['bankName'])->find()['bankPhoto'];
            }
            $list=$res['cards'];
        }
//var_dump($list);
        $this->assign('list',$list);
        return $this->fetch('Recharge/uppage');
    }

    //签约银行卡
    public function  pageadd()
    {
        $data=Db::name('user_certification')->where('uid='.Session::get('uid').' and status=1')->find();
        $this->assign('data',$data);
        return $this->fetch('Recharge/pageadd');
    }
    //开始签约
    public function pageadds()
    {
//  	$toamount=$_GET['toamount'];
        $ste =$this->request->post();
        $ste=myarr($ste);
        if($ste['code']!=0)
        {
            $tres=Session::get('tres');
            if(isset($tres['token'])){
                //流水号
                //var_dump($ste)
                $order=orderNum();
                //$str="version=1.0.0&transCod=BQP0001&reqSeq=201806121347&merCode=330100710271&chainNo=004&merCustId=21&name=阳孟&certType=0&certNo=420582199502165093&phone=18672926310&cardType=D&cardNo=6228480059557390271&validDate=&cvv2=&verCode=&token=&phoneToken=";
                $str="version=1.0.0&transCode=BQP0001&reqSeq=".$order."&merCode=330100710271&chainNo=004&merCustId=".Session::get('uid')."&name=".$ste['name']."&certType=0&certNo=".$ste['cer']."&phone=".$ste['phone']."&cardType=D&cardNo=".$ste['card']."&validDate=&cvv2=&verCode=".$ste['code']."&token=".$tres['token']."&phoneToken=".$tres['phoneToken'];

                $pfxpath='http://test.lcqjgj.com/static/home/lc.pfx';
                $pfxpwd='Lczc_164';
                $sign=$this->sign(iconv('UTF-8','GBK',$str),$pfxpath,$pfxpwd);
                //var_dump($sign);
                $data='{
				"version":"1.0.0",
				"transCode":"BQP0001",
				"reqSeq":"'.$order.'",
				"merCode":"330100710271",
				"chainNo":"004",
				"merCustId":"'.Session::get('uid').'",
				"name":"'.$ste['name'].'",
				"certType":"0",
				"certNo":"'.$ste['cer'].'",
				"phone":"'.$ste['phone'].'",
				"cardType":"D",
				"cardNo":"'.$ste['card'].'",
				"validDate":"",
				"cvv2":"",
				"verCode":"'.$ste['code'].'",
				"token":"'.$tres['token'].'",
				"phoneToken":"'.$tres['phoneToken'].'",
				"sign":"'.$sign.'"
				}';
                $data=iconv('UTF-8','GBK',$data);
                $data=base64_encode($data);
                $data=str_replace('+','#',$data);  //+替换成#
                $url='https://hpay.96225.com/HzsmkBQPay/merBQPay.do';
                $res=$this->https_request($url,$data);
                //$res=iconv('GBK','UTF-8',$res);
                $res=json_decode($res,true);
                //是否签约成功
                if($res['respDesc']=="成功")
                {
                    return  "<script>alert('签约成功');window.location.href='/home/Recharge/recharge'</script>";
                }else{
                    return  "<script>alert('签约银行卡失败');history.go(-1)</script>";
                }
            }else
            {
                return  "<script>alert('验证码错误');history.go(-1)</script>";
            }

        }else{

            //流水号
            $order=orderNum();
            //$str="version=1.0.0&transCod=BQP0001&reqSeq=201806121347&merCode=330100710271&chainNo=004&merCustId=21&name=阳孟&certType=0&certNo=420582199502165093&phone=18672926310&cardType=D&cardNo=6228480059557390271&validDate=&cvv2=&verCode=&token=&phoneToken=";
            $str="version=1.0.0&transCode=BQP0001&reqSeq=".$order."&merCode=330100710271&chainNo=004&merCustId=".Session::get('uid')."&name=".$ste['name']."&certType=0&certNo=".$ste['cer']."&phone=".$ste['phone']."&cardType=D&cardNo=".$ste['card']."&validDate=&cvv2=&verCode=&token=&phoneToken=";
            $pfxpath='http://test.lcqjgj.com/static/home/lc.pfx';
            $pfxpwd='Lczc_164';
            $sign=$this->sign(iconv('UTF-8','GBK',$str),$pfxpath,$pfxpwd);
            //var_dump($sign);
            $data='{
				"version":"1.0.0",
				"transCode":"BQP0001",
				"reqSeq":"'.$order.'",
				"merCode":"330100710271",
				"chainNo":"004",
				"merCustId":"'.Session::get('uid').'",
				"name":"'.$ste['name'].'",
				"certType":"0",
				"certNo":"'.$ste['cer'].'",
				"phone":"'.$ste['phone'].'",
				"cardType":"D",
				"cardNo":"'.$ste['card'].'",
				"validDate":"",
				"cvv2":"",
				"verCode":"",
				"token":"",
				"phoneToken":"",
				"sign":"'.$sign.'"
				}';
            $data=iconv('UTF-8','GBK',$data);
            $data=base64_encode($data);
            $data=str_replace('+','#',$data);  //+替换成#
            $url='https://hpay.96225.com/HzsmkBQPay/merBQPay.do';
            $res=$this->https_request($url,$data);
            //return $res;
            //$res=iconv('GBK','UTF-8',$res);
            $res=json_decode($res,true);
            if(!isset($res['token'])){
                $res['token']='';
            }
            if(!isset($res['phoneToken'])){
                $res['phoneToken']='';
            }
            Session::set('tres',$res);
            //return Session::get('tres');
            return $res;
        }

    }

    //支付
    public function thepage()
    {
        $ste = $this->request->post();
        $ste=myarr($ste);
        //var_dump($ste);
        $ste['vimg']=substr($ste['cerdid'], 10);
        $ste['cerdid']=substr($ste['cerdid'],0,10);
        //var_dump($ste);die;
        //生成订单
        $this->assign('ste',$ste);
        return $this->fetch('Recharge/thepage');

    }

    //支付第一次请求
    public function the()
    {
        $list = $this->request->post();
        $list=myarr($list);
        //支付-BQP003
        if($list['code']!=0)
        {
            $order=Session::get('order');
            //订单号
            $orderid=Session::get('orderid');
            $time=Session::get('time');
            //return  111;
            $tokens=Session::get('tokens');
            //var_dump($tokens);die;
            if(isset($tokens['phoneToken']))
            {
                $list['toamount']=$list['toamount']*100;
                $str="version=1.0.0&transCode=BQP0003&reqSeq=".$order."&merCode=330100710271&chainNo=004&orderNo=".$orderid."&merCustId=".Session::get('uid')."&shortCardNo=".$list['cerdid']."&dateTime=".$time."&amount=".$list['toamount']."&goods=充值&verCode=".$list['code']."&phoneToken=".$tokens['phoneToken'];
                //var_dump(1111);
                $pfxpath='http://test.lcqjgj.com/static/home/lc.pfx';
                $pfxpwd='Lczc_164';
                $sign=$this->sign(iconv('UTF-8','GBK',$str),$pfxpath,$pfxpwd);
                //var_dump(222222);die;
                $data='{
	    		"version":"1.0.0",
	    		"transCode":"BQP0003",
	    		"reqSeq":"'.$order.'",
	    		"merCode":"330100710271",
	    		"chainNo":"004",
	    		"orderNo":"'.$orderid.'",
	    		"merCustId":"'.Session::get('uid').'",
	    		"shortCardNo":"'.$list['cerdid'].'",
	    		"dateTime":"'.$time.'",
	    		"amount":"'.$list['toamount'].'",
	    		"goods":"充值",
	    		"verCode":"'.$list['code'].'",
	    		"phoneToken":"'.$tokens['phoneToken'].'",
	    		"sign":"'.$sign.'"
    	     }';
                //var_dump($data);
                $data=iconv('UTF-8','GBK',$data);
                $data=base64_encode($data);
                $data=str_replace('+','#',$data);  //+替换成#
                $url='https://hpay.96225.com/HzsmkBQPay/merBQPay.do';
                $res=$this->https_request($url,$data);
                $res=json_decode($res,true);
                //var_dump($res);die;
                //判断验证码是否发送正确
                if(isset($res['status']))
                {
                    if($res['status']=="01")
                    {
                        //查询用户余额
                        $price=Db::name('users')->where('id='.Session::get('uid'))->field('balance')->find();
                        //充值的金额
                        $lists=$list['toamount']*0.01-$list['charge'];
                        //一共总余额
                        $price=$price['balance']+$lists;
                        //更新用户数据
                        Db::table('qfll_users')->where('id',Session::get('uid'))->setField('balance', $price);
                        //资金日志
                        $zprice=Db::name('cashlog')->where('uid',Session::get('uid'))->order('id', 'desc')->limit(0,1)->find();
                        $zprice=$zprice['balance']+$lists;
                        $data = ['uid' =>Session::get('uid'), 'type' => '1' , 'price' => $lists , 'balance'=>$zprice];
                        Db::table('qfll_cashlog')->insert($data);
                        //充值表
                        $paymenttime=date('Y-m-d H:i:s');
                        $data = ['uid' =>Session::get('uid'), 'tradeNo'=>$res['orderNo'],'platformtradeNo' => $res['serialNo'] ,'amount'=>$lists,'paymentCode'=>5,'offline'=>1,'paymentstate'=>1,'poundage'=>$list['charge'],'paymenttime'=>$paymenttime, ];
                        Db::table('qfll_user_recharge')->insert($data);
                        //var_dump($res);die;
                        $this->success('支付成功!','/home/Openanaccount/index');
                    }
                    if($res['status']=="02")
                    {
                        $this->success('支付失败!','/home/Recharge/recharge');
                    }
                    if($res['status']=="03")
                    {
                        $data=array();
                        $data['uid']=Session::get('uid');
	         	$data['amount']=$list['toamount']*0.01-$list['charge'];
	         	$data['reqSeq']=$res['reqSeq'];
	         	$data['serialNo']=$res['serialNo'];
	         	$data['dateTime']=$res['dateTime'];
	         	$data['del']=2;
	         	Db::name('cerid')->insert($data);
	         	$this->success('银行处理中!','/home/userpersonal/personalCenter');
	         }
                }else{
                    return   "<script>alert('验证码错误');history.go(-2);</script>";
                }

            }else
            {
                return  "<script>alert('请先发送验证码');history.go(-1)</script>";
            }
        }else{
            //流水号
            $order=date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
            //订单号
            $orderid=orderNum();
            $time=date('Ymd H:i:s');
            Session::set('order',$order);
            Session::set('orderid',$orderid);
            Session::set('time',$time);
            $list['toamount']=$list['toamount']*100;
            $str="version=1.0.0&transCode=BQP0003&reqSeq=".$order."&merCode=330100710271&chainNo=004&orderNo=".$orderid."&merCustId=".Session::get('uid')."&shortCardNo=".$list['cerdid']."&dateTime=".$time."&amount=".$list['toamount']."&goods=充值&verCode=&phoneToken=";
            //var_dump(1111);
            $pfxpath='http://test.lcqjgj.com/static/home/lc.pfx';
            $pfxpwd='Lczc_164';
            $sign=$this->sign(iconv('UTF-8','GBK',$str),$pfxpath,$pfxpwd);
            //var_dump(222222);die;
            $data='{
	    		"version":"1.0.0",
	    		"transCode":"BQP0003",
	    		"reqSeq":"'.$order.'",
	    		"merCode":"330100710271",
	    		"chainNo":"004",
	    		"orderNo":"'.$orderid.'",
	    		"merCustId":"'.Session::get('uid').'",
	    		"shortCardNo":"'.$list['cerdid'].'",
	    		"dateTime":"'.$time.'",
	    		"amount":"'.$list['toamount'].'",
	    		"goods":"充值",
	    		"verCode":"",
	    		"phoneToken":"",
	    		"sign":"'.$sign.'"
    	     }';
            //return $data;
            $data=iconv('UTF-8','GBK',$data);
            $data=base64_encode($data);
            $data=str_replace('+','#',$data);  //+替换成#
            $url='https://hpay.96225.com/HzsmkBQPay/merBQPay.do';
            $res=$this->https_request($url,$data);
            //file_put_contents('./res.txt',$res);
            $res=json_decode($res,true);
           // var_dump($res);die;
            Session::set('tokens',$res);
            return $res;
        }

    }

    //银行卡解约
    public function  forfeit(){
        $cardid =$_GET['cardid'];
        //流水号
        $order=date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
        $str="version=1.0.0&transCode=BQP0002&reqSeq=20180612513956744&merCode=330100710271&chainNo=004&merCustId=".Session::get('uid')."&shortCardNo=".$cardid;
        $pfxpath='http://test.lcqjgj.com/static/home/lc.pfx';
        $pfxpwd='Lczc_164';
        $sign=$this->sign(iconv('UTF-8','GBK',$str),$pfxpath,$pfxpwd);
        //var_dump($sign);
        $data='{
							"version":"1.0.0",
							"transCode":"BQP0002",
							"reqSeq":"20180612513956744",
							"merCode":"330100710271",
							"chainNo":"004",
						  "merCustId":"'.Session::get('uid').'",
						  "shortCardNo":"'.$cardid.'",
						  "sign":"'.$sign.'",
             }';
        $data=iconv('UTF-8','GBK',$data);
        $data=base64_encode($data);
        $data=str_replace('+','#',$data);  //+替换成#
        $url='https://hpay.96225.com/HzsmkBQPay/merBQPay.do';
        $res=$this->https_request($url,$data);
        //$res=iconv('GBK','UTF-8',$res);
        $res=json_decode($res,true);
        //是否签约成功
        if($res['respCode']=='00'){
            return  "<script>alert('解约成功');history.go(-1)</script>";
        }else{
            return  "<script>alert('解约失败');history.go(-1)</script>";
        }


    }



//  加签方法
    public function sign($data,$pfxpath,$pfxpwd)
    {
        $certs = array();
        openssl_pkcs12_read(file_get_contents($pfxpath), $certs, $pfxpwd);
        // 其中password为你的证书密码
        if (!$certs){
            return;
        }
        $signature = '';
        openssl_sign($data, $signature, $certs['pkey']);
        return base64_encode($signature);
    }

//网站请求
    function https_request($url,$data = null)
    {
        // php curl 发起get或者post请求
        // curl 初始化
        $curl = curl_init();	// curl 设置
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);

        // 判断 $data get  or post
        if ( !empty($data) ) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }

        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

        // 执行
        $res = curl_exec($curl);
        curl_close($curl);
        return $res;
    }
}